/*
 * Copyright (c) 2025 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include "sit_writer.h"

#include <string>
#include <sys/types.h>
#include <cinttypes>

#include "hmfs_utils.h"
#include "mkfs_format.h"
#include "securec.h"
#include "device_manager.h"
#include "hmfs_io.h"
#include "hmfs_common.h"

namespace OHOS {
namespace Hmfs {

SitWriter::SitWriter(HmfsMkfs *mkfs) : mkfs_(mkfs)
{
}

int32_t SitWriter::Prepare()
{
    return 0;
}

int32_t SitWriter::Write()
{
    HmfsData& hmfsData = mkfs_->hmfsData_;
    uint32_t segmentSize = BLOCKS_PER_SEGMENT * HMFS_BLOCK_SIZE;
    auto buf = std::make_unique<uint8_t[]>(segmentSize);
    if (buf == nullptr) {
        HMFS_ERROR("not enough memory for sit segment!");
        return -1;
    }
    memset_s(buf.get(), segmentSize, 0, segmentSize);

    uint64_t offset = hmfsData.sitStartBlkId * HMFS_BLOCK_SIZE;
    for (uint32_t i = 0; i < (hmfsData.segmentCountInSIT / 2); i++) {
        if (HmfsIo::GetInstance().DevFill(buf.get(), offset, segmentSize)) {
            HMFS_ERROR("failed to write sit segment!");
            return -1;
        }
        offset += segmentSize;
    }

    return 0;
}

} // namespace Hmfs
} // namespace OHOS
